package com.fs.controller.v2;

import com.fs.controller.vo.room.VoBookedTime;
import com.fs.global.init.RoleName;
import com.fs.service.PurchaseService;
import com.fs.service.bo.purchase.BoRoomBookedTime;
import com.fs.utils.Utils;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.bson.Document;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "房间详情", description = "微信小程序用户使用")
@RestController("/v2/room")
@RequiresRoles(value = {RoleName.GUEST, RoleName.CUSTOMER}, logical = Logical.OR)
public class RoomDetailController {

    private final MongoClient client;
    private final PurchaseService purchaseService;

    public RoomDetailController(MongoClient client, PurchaseService purchaseService) {
        this.client = client;
        this.purchaseService = purchaseService;
    }

    @ApiOperation("获取房间文字描述")
    @GetMapping("/detail")
    public String queryRoomDesc(@RequestParam("roomId") Integer roomId) {
        MongoDatabase db = client.getDatabase("rooms");
        MongoCollection<Document> blogs = db.getCollection("rooms");
        Document res = blogs.find(Filters.eq("id", roomId)).first();
        if (res == null) {
            return "";
        }
        return res.toJson();
    }

    @ApiOperation("获取未来三天房间已被占用时段")
    @GetMapping("/occupied-time")
    public Map<String, List<VoBookedTime>> getOccupiedTimes(@RequestParam("roomId") Integer roomId) {
        LocalDate today = LocalDate.now();
        Map<String, List<VoBookedTime>> map = new HashMap<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        for (int i = 0; i < 3; i++) {
            LocalDate date = today.plusDays(i);
            List<BoRoomBookedTime> bookedTimes = purchaseService.getBookedTimeByRoomAndDate(roomId, date);
            List<VoBookedTime> times = bookedTimes.stream().map(bo -> {
                VoBookedTime vo = new VoBookedTime();
                vo.setStart(Utils.localDateTimeToString(bo.getStart()));
                vo.setEnd(Utils.localDateTimeToString(bo.getEnd()));
                return vo;
            }).collect(Collectors.toList());
            map.put(formatter.format(date), times);
        }
        return map;
    }


}
